import {
  allCrewServices,
  clearCourseCrewServices,
  courseAllocation,
  getCrew,
} from '@/services/supervisionApi';
import type { ProColumns } from '@ant-design/pro-components';
import { EditableProTable, PageContainer } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Button, message } from 'antd';
import React, { useEffect, useState } from 'react';

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

interface Course {
  id: Number;
  classroomLocation: string;
  // 其他字段...
}

type DataSourceType = {
  id: React.Key;
  title?: string;
  readonly?: string;
  decs?: string;
  state?: string;
  created_at?: number;
  update_at?: number;
  children?: DataSourceType[];
  assignsRoom?: string | number;
};

const defaultData: DataSourceType[] = [
  {
    id: 624748504,
    title: '活动名称一',
    readonly: '活动名称一',
    decs: '这个活动真好玩',
    state: 'open',
    created_at: 1590486176000,
    update_at: 1590486176000,
  },
  {
    id: 624691229,
    title: '活动名称二',
    readonly: '活动名称二',
    decs: '这个活动真好玩',
    state: 'closed',
    created_at: 1590481162000,
    update_at: 1590481162000,
  },
];

export default () => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly DataSourceType[]>([]);
  const [position, setPosition] = useState<'top' | 'bottom' | 'hidden'>('bottom');
  const [crewInfo, setAllCrewInfo] = useState<any>([]);
  // 是否禁用清空按钮
  const [isDisableEmpty, setIsDisableEmpty] = useState(false);

  const allCrewInfo = useRequest(allCrewServices, {
    manual: true,
    onSuccess: (data) => {
      console.log('data', data);
      setAllCrewInfo(data);
    },
  });

  // clearLeaderCrew
  const clearCrewCourse = useRequest(clearCourseCrewServices, {
    manual: true,
    onSuccess: (data) => {
      console.log('data', data);
    },
  });

  // 判断当前时间是否为 周六日 如果是 就禁用清空按钮
  const DisableEmptyBtn = () => {
    const currentDate = new Date();
    // 当前是周几
    const currentDay = currentDate.getDay();
    // 如果是周六或者周日
    if (currentDay === 0 || currentDay === 6){
      console.log(currentDay);
      
      setIsDisableEmpty(true)
    }else {
      setIsDisableEmpty(false)
    }
  };

  useEffect(() => {
    allCrewInfo.run();
    DisableEmptyBtn()
  }, []);

  // 自定义排序函数
  const customSorter = (a: Course, b: Course) => {
    // 提取房间号和前缀
    const extractRoomNumber = (location: string) => {
      const match = location.match(/([a-zA-Z]+)(\d+)/);
      if (match) {
        return { prefix: match[1], number: parseInt(match[2], 10) };
      }
      return { prefix: '', number: 0 };
    };

    const aRoom = extractRoomNumber(a.classroomLocation);
    const bRoom = extractRoomNumber(b.classroomLocation);

    // 首先按前缀排序
    if (aRoom.prefix !== bRoom.prefix) {
      return aRoom.prefix.localeCompare(bRoom.prefix);
    }

    // 如果前缀相同，按数字排序
    return aRoom.number - bRoom.number;
  };

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      hideInSearch: true,
      width: 70,
      readonly: true,
    },
    {
      title: '上课地点',
      dataIndex: 'classroomLocation',
      key: 'classroomLocation',
      hideInSearch: true,
      // width: 200,
      readonly: true,
    },
    {
      title: '开课课程',
      dataIndex: 'courseName',
      key: 'courseName',
      hideInSearch: true,
      // width: 200,
      readonly: true,
    },
    {
      title: '上课班级',
      dataIndex: 'classNumber',
      key: 'classNumber',
      hideInSearch: true,
      // width: 320,
      readonly: true,
    },
    {
      title: '授课教师',
      dataIndex: 'instructor',
      key: 'instructor',
      hideInSearch: true,
      readonly: true,
    },
    {
      title: '分配教室',
      dataIndex: 'assignsRoom',
      key: 'assignsRoom',
      tooltip: '只要在你为组员分配教师 之后 组员才有记录',
      hideInSearch: true,
      valueType: 'select',
      valueEnum: crewInfo,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];

  return (
    <>
      <PageContainer title="组员管理">
        <EditableProTable<DataSourceType>
          rowKey="id"
          // headerTitle="组员管理"
          maxLength={5}
          scroll={{
            x: 960,
          }}
          recordCreatorProps={false}
          loading={false}
          toolBarRender={() => {
            return isDisableEmpty ? []: [
              <Button
                type="primary"
                danger
                onClick={() => {
                  clearCrewCourse.run();
                }}
                disabled={isDisableEmpty}
              >
                清空
              </Button>,
            ]
          }}
          columns={columns}
          request={(params, sort) => getCrew()}
          value={dataSource}
          onChange={setDataSource}
          editable={{
            type: 'multiple',
            editableKeys,
            onSave: async (rowKey, data, row) => {
              console.log('rowKey', rowKey, 'data', data, 'row', row);
              await courseAllocation({
                crewId: String(data.assignsRoom),
                courseId: String(data.id),
              });
            },
            onChange: setEditableRowKeys,
          }}
        />
      </PageContainer>
    </>
  );
};
